import { uploadFileOther } from '/@/api/support/file-api.js'
import { message } from 'ant-design-vue'

// 构建上传成功的文件对象
const buildFormattedFile = (fileObj, response) => ({
  uid: fileObj.uid,
  name: fileObj.name,
  status: 'done',
  url: response?.data?.url || response?.data?.path,
  res: response?.data,
})

// 上传文件自定义的方法
export const myUpload = (requestObj, options) => {
  const opt = {
    apiFunc: uploadFileOther,
    apiData: {},
    ...options,
  }
  return new Promise((resolve, reject) => {
    // 检查文件对象是否有效
    if (!requestObj || !requestObj.file) {
      return reject(new Error('缺少有效的文件对象'))
    }

    const fileObj = requestObj.file

    // 使用 FileReader 将文件转换为 Base64
    const reader = new FileReader()
    reader.onload = async (e) => {
      try {
        const base64Data = e.target.result.split(',')[1]

        const myData = typeof opt.apiData === 'function' ? opt.apiData({ ...fileObj, base64Data }) : opt.apiData
        // 构建请求数据
        const uploadData = {
          fileName: fileObj.name, // 文件名
          file: base64Data, // 去掉前缀的 Base64 数据
          ...myData,
        }

        // 调用上传函数
        const response = await opt.apiFunc(uploadData)
        // 检查上传是否成功
        if (response.data && response.code === 200) {
          const formattedFile = buildFormattedFile(fileObj, response)
          requestObj.onSuccess(response?.data?.url || response?.data?.path || response?.data, requestObj.file)
          resolve(formattedFile)
        } else {
          const errorMessage = response?.data?.message || response?.data?.msg || response?.msg || '上传失败'
          requestObj.onError()
          message.error(errorMessage)
          reject(new Error(errorMessage))
        }
      } catch (error) {
        requestObj.onError()
        console.error(error)
        message.error(`上传过程中发生错误,错误信息:${error}`)
        reject(error)
      }
    }

    reader.onerror = () => {
      const error = new Error('文件读取失败')
      requestObj.onError()
      message.error('文件读取失败')
      reject(error)
    }

    // 读取文件为 Data URL
    reader.readAsDataURL(fileObj)
  })
}
